package legumes.client.ui.widgets.map;

import java.util.ArrayList;
import java.util.List;

import legumes.client.resources.CommonProperties;

import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.control.MapTypeControl;
import com.google.gwt.maps.client.geom.LatLng;

public class MapFactory {

	private static MapFactory s_instance;
	private List<Runnable> onMapLoadedRunnableList;
	private boolean mapLoaded = false;
	private boolean mapLoadingAPI = false;
	
	/**
	 * Method loadMapLibrary must be called before using map widget
	 * @return
	 */
	public static MapFactory getInstance(){
		if(s_instance==null){
			s_instance = new MapFactory();
		}
		return s_instance;
	}
	
	private MapFactory(){
		onMapLoadedRunnableList = new ArrayList<Runnable>();
	}
	
	/**
	 * Must be called before using map widgets
	 * @param onMapLoaded_
	 */
	public void loadMapLibrary(Runnable onMapLoaded_){
		if(!mapLoaded){
			onMapLoadedRunnableList.add(onMapLoaded_);
			if(!mapLoadingAPI){
				mapLoadingAPI = true;
				Maps.loadMapsApi(
						CommonProperties.GOOGLE_MAPS_KEY, 
						CommonProperties.GOOGLE_MAPS_API_VERSION, 
						true, 
						new Runnable() {
							
							@Override
							public void run() {
								onMapLoaded();
							}
						}
				);
			}
		} else {
			onMapLoaded_.run();
		}
	}
	
	private void onMapLoaded(){
		mapLoaded = true;
		
		for(Runnable r : onMapLoadedRunnableList){
			r.run();
		}
	}
	
	public MapWidget createMapWidgetWithoutCtrl(LatLng center_, int width_, int height_){
		MapWidget map = new MapWidget(center_, 10);
		map.setSize(width_ + "px", height_ + "px");
		// Add some controls for the zoom level
//		LargeMapControl lmc = ;
//		map.addControl(new LargeMapControl());
//		map.addControl(new MapTypeControl());
//		map.addControl(new ScaleControl());
		return map;
	}
	
	public MapWidget createMapWidget(LatLng center_, int width_, int height_){
		MapWidget map = new MapWidget(center_, 10);
		map.setSize(width_ + "px", height_ + "px");
		// Add some controls for the zoom level
//		LargeMapControl lmc = ;
		map.addControl(new LargeMapControl());
		map.addControl(new MapTypeControl());
//		map.addControl(new ScaleControl());
		return map;
	}
}
